<template>
  <div v-if="readOnly">
    <a-row>
      <a-col :span="24">
        <a-space>
          <span>{{ `${formData.beginDate} 00:00:00 至 ${formData.endDate} 23:59:59` }}</span>
          <span>
            <a-checkbox :disabled="readOnly" v-model:checked="cycleFlag" @change="cycleTypeChange">
              <span>按周期</span>
            </a-checkbox>
          </span>
        </a-space>
      </a-col>
    </a-row>
    <a-row v-if="cycleFlag" style="padding-top: 10px">
      <a-col :span="24">
        <div style="background-color: rgb(245, 248, 250); padding-left: 20px">
          <a-form>
            <a-form-item label="执行周期">
              <a-space>
                <span>{{ _This().$enums.CYCLE_TYPE.getDesc(cycleType) }}</span>
                [
                <span v-if="cycleType === 2">
                  {{
                    weekOptions
                      .filter((item) => cycleTimeRule.includes(item.value))
                      .map((item) => item.label)
                      .join('、')
                  }}
                </span>
                <span v-if="cycleType === 3">
                  {{
                    [...Array(31)]
                      .map((_, i) => ({
                        label: i + 1 + '日',
                        value: i + 1,
                      }))
                      .filter((item) => cycleTimeRule.includes(item.value))
                      .map((item) => item.label)
                      .join('、')
                  }}
                </span>
                ]
              </a-space>
            </a-form-item>
            <a-form-item label="执行时间段">
              <a-row v-for="(item, index) in cycleTimeGroup" :key="index">
                <a-col :span="24">
                  {{ `${item.beginTime} 至 ${item.endTime}` }}
                </a-col>
              </a-row>
            </a-form-item>
          </a-form>
        </div>
      </a-col>
    </a-row>
  </div>
  <a-form
    v-else
    ref="form"
    :label-col="{ span: 4 }"
    :wrapper-col="{ span: 18 }"
    :model="formData"
    :rules="rule"
  >
    <a-form-item label="活动时间" name="endDate">
      <a-row>
        <a-col :span="12">
          <a-range-picker
            style="width: 100%"
            :value="[beginDate ? dayjs(beginDate) : null, endDate ? dayjs(endDate) : null]"
            :presets="[
              { label: '今天', value: [dayjs(), dayjs()] },
              { label: '最近3天', value: [dayjs(), dayjs().add(3, 'day')] },
              { label: '最近7天', value: [dayjs(), dayjs().add(7, 'day')] },
              { label: '最近30天', value: [dayjs(), dayjs().add(30, 'day')] },
              { label: '最近90天', value: [dayjs(), dayjs().add(90, 'day')] },
              { label: '最近180天', value: [dayjs(), dayjs().add(180, 'day')] },
              { label: '最近365天', value: [dayjs(), dayjs().add(365, 'day')] },
            ]"
            @change="
              (val) => {
                beginDate = val?.[0]?.format('YYYY-MM-DD');
                endDate = val?.[1]?.format('YYYY-MM-DD');
              }
            "
            allow-clear
          />
        </a-col>
        <a-col :span="12">
          <div style="padding-left: 30px; padding-top: 3px">
            <a-form-item-rest>
              <a-checkbox v-model:checked="cycleFlag" @change="cycleTypeChange">
                <span>按周期</span>
                <span style="padding-left: 30px">勾选后即可填写下方执行时间段、执行周期</span>
              </a-checkbox>
            </a-form-item-rest>
          </div>
        </a-col>
      </a-row>
    </a-form-item>
    <a-form-item label=" " :colon="false" v-if="cycleFlag">
      <div style="background-color: rgb(245, 248, 250); padding-left: 20px">
        <a-form-item label="执行周期" name="cycleType">
          <a-select
            style="padding-left: 12px; padding-top: 5px; width: 260px"
            v-model:value="cycleType"
            allow-clear
          >
            <a-select-option
              v-for="item in _This().$enums.CYCLE_TYPE.values()"
              :key="item.code"
              :value="item.code"
              >{{ item.desc }}</a-select-option
            >
          </a-select>
          <div style="padding-top: 10px">
            <a-checkbox-group
              v-if="cycleType === 2"
              v-model:value="cycleTimeRule"
              :options="weekOptions"
            />
            <a-select
              v-if="cycleType === 3"
              style="padding-left: 12px; padding-top: 5px; width: 260px"
              mode="multiple"
              v-model:value="cycleTimeRule"
              :options="
                [...Array(31)].map((_, i) => ({
                  label: (i + 1).toString().padStart(2, '0'),
                  value: i + 1,
                }))
              "
              placeholder="请选择每月日"
              allow-clear
            />
          </div>
        </a-form-item>
        <a-form-item label="执行时间段" v-if="formData.cycleTimeGroup.length > 0" required>
          <a-form-item
            v-for="(item, index) in formData.cycleTimeGroup"
            :key="index"
            :name="['cycleTimeGroup', index, 'endTime']"
            :rules="[
              { required: true, message: '请选择时间段', trigger: ['change'] },
              {
                validator: (rule, value, callback) => {
                  cycleTimeValidator(index, rule, value) ? callback('时间段错误') : callback();
                },
                trigger: ['change'],
              },
            ]"
          >
            <a-row>
              <a-col :span="24">
                <span>
                  <a-time-range-picker
                    style="width: 250px"
                    format="HH:mm"
                    :value="[
                      item.beginTime ? dayjs(item.beginTime, 'HH:mm') : null,
                      item.endTime ? dayjs(item.endTime, 'HH:mm') : null,
                    ]"
                    @change="
                      (val) => {
                        item.beginTime = val?.[0]?.format('HH:mm');
                        item.endTime = val?.[1]?.format('HH:mm');
                      }
                    "
                    allow-clear
                  />
                </span>
                <span style="padding-left: 5px">
                  <a-button
                    type="link"
                    @click="
                      () => {
                        formData.cycleTimeGroup.splice(index, 1);
                      }
                    "
                    danger
                    >删除</a-button
                  >
                </span>
              </a-col>
            </a-row>
          </a-form-item>
        </a-form-item>
        <a-form-item>
          <div style="padding-bottom: 10px">
            <a-button
              style="width: 370px"
              type="dashed"
              @click="
                () =>
                  formData.cycleTimeGroup.push({
                    beginTime: '',
                    endTime: '',
                  })
              "
              block
            >
              新增时间段
            </a-button>
          </div>
        </a-form-item>
      </div>
    </a-form-item>
  </a-form>
</template>

<script setup>
  import { computed, getCurrentInstance, ref } from 'vue';
  import dayjs from 'dayjs';

  // this对象
  const instance = getCurrentInstance();

  const beginDate = defineModel('beginDate');

  const endDate = defineModel('endDate');

  const cycleFlag = defineModel('cycleFlag');

  const cycleType = defineModel('cycleType');

  const props = defineProps({
    readOnly: {
      type: Boolean,
      default: false,
    },
  });

  const weekOptions = [
    { label: '周一', value: 1 },
    { label: '周二', value: 2 },
    { label: '周三', value: 3 },
    { label: '周四', value: 4 },
    { label: '周五', value: 5 },
    { label: '周六', value: 6 },
    { label: '周日', value: 7 },
  ];

  const cycleTypeChange = () => {
    if (!cycleFlag.value) {
      initCycleData();
    }
  };

  const cycleTimeGroup = defineModel('cycleTimeGroup', {
    default: () => [],
  });

  const cycleTimeRule = defineModel('cycleTimeRule', {
    default: () => [],
  });

  const initCycleData = () => {
    cycleType.value = 1;
    cycleTimeGroup.value = [{ beginTime: '00:00', endTime: '23:59' }];
    cycleTimeRule.value = [];
  };

  const formData = computed(() => {
    return {
      beginDate: beginDate.value,
      endDate: endDate.value,
      cycleFlag: cycleFlag.value,
      cycleType: cycleType.value,
      cycleTimeGroup: cycleTimeGroup.value,
    };
  });

  const rule = ref({
    endDate: [{ required: true, message: '请选择活动时间', trigger: ['change'] }],
    cycleType: [{ required: true, message: '请选择执行周期', trigger: ['change'] }],
  });

  const form = ref();

  const cycleTimeValidator = (index, rule, value) => {
    console.log(index, rule, value);

    let stratTime = cycleTimeGroup.value[index].beginTime;
    let endTime = cycleTimeGroup.value[index].endTime;

    let res = cycleTimeGroup.value.filter((item, i) => {
      if (index !== i) {
        return isAfter(stratTime, endTime, item.beginTime, item.endTime);
      }
    }).length;

    return res !== 0;
  };

  const isAfter = (interval1Start, interval1End, interval2Start, interval2End) => {
    if (interval1Start && interval1End && interval2Start && interval2End) {
      let startTime1 = dayjs(interval1Start + ':00', 'HH:mm:ss').valueOf();
      let endTime1 = dayjs(interval1End + ':59', 'HH:mm:ss').valueOf();
      let startTime2 = dayjs(interval2Start + ':00', 'HH:mm:ss').valueOf();
      let endTime2 = dayjs(interval2End + ':59', 'HH:mm:ss').valueOf();

      // 如果一个时间段的结束时间小于另一个时间段的开始时间，那么它们没有交集
      if (endTime1 < startTime2 || endTime2 < startTime1) {
        return false;
      }
      // 否则，它们有交集
      return true;
    }
    return false;
  };

  const validateForm = () => {
    return form.value.validate();
  };

  // 组件实例对象
  const _This = () => {
    return instance.appContext.config.globalProperties;
  };

  defineExpose({
    validateForm,
  });
</script>

<style scoped></style>
